const CACHE_NAME = 'ai-camera-v1';
const OFFLINE_URL = './offline.html';

// 需要缓存的资源列表
const urlsToCache = [
  './',
  './index.html',
  './offline.html',
  './manifest.json',
  './assets/css/index.css',
  './assets/css/snake-spinner.css',
  './assets/css/drawer.css',
  './assets/js/app.js',
  './assets/libs/tfjs.min.js',
  './assets/libs/posenet.min.js',
  './assets/libs/jquery.min.js',
  './assets/icon/down-arrow.svg',
  './assets/icon/app-icon-192.png',
  './assets/icon/app-icon-512.png'
];

// 安装 Service Worker
self.addEventListener('install', event => {
  event.waitUntil(
    Promise.all([
      // 缓存核心资源
      caches.open(CACHE_NAME).then(cache => {
        return cache.addAll(urlsToCache);
      }),
      // 强制激活
      self.skipWaiting()
    ])
  );
});

// 激活 Service Worker
self.addEventListener('activate', event => {
  event.waitUntil(
    Promise.all([
      // 清理旧缓存
      caches.keys().then(cacheNames => {
        return Promise.all(
          cacheNames.map(cacheName => {
            if (cacheName !== CACHE_NAME) {
              return caches.delete(cacheName);
            }
          })
        );
      }),
      // 立即接管所有页面
      self.clients.claim()
    ])
  );
});

// 处理请求
self.addEventListener('fetch', event => {
  // 只处理 GET 请求
  if (event.request.method !== 'GET') return;

  event.respondWith(
    caches.match(event.request)
      .then(response => {
        // 返回缓存的资源（如果有）
        if (response) {
          return response;
        }

        // 克隆请求因为请求只能使用一次
        const fetchRequest = event.request.clone();

        return fetch(fetchRequest)
          .then(response => {
            // 检查响应是否有效
            if (!response || response.status !== 200 || response.type !== 'basic') {
              return response;
            }

            // 克隆响应因为响应体只能使用一次
            const responseToCache = response.clone();

            // 将新响应添加到缓存
            caches.open(CACHE_NAME)
              .then(cache => {
                cache.put(event.request, responseToCache);
              });

            return response;
          })
          .catch(() => {
            // 如果离线且请求HTML页面，返回离线页面
            if (event.request.mode === 'navigate') {
              return caches.match(OFFLINE_URL);
            }
          });
      })
  );
});

// 处理推送通知
self.addEventListener('push', event => {
  const options = {
    body: event.data.text(),
    icon: './assets/icon/app-icon-192.png',
    badge: './assets/icon/badge-icon.png',
    vibrate: [100, 50, 100],
    data: {
      dateOfArrival: Date.now(),
      primaryKey: '1'
    }
  };

  event.waitUntil(
    self.registration.showNotification('AI摄像头通知', options)
  );
});